package com.xdap.keymen.service.punch;

import com.definesys.mpaas.query.MpaasQuery;
import com.definesys.mpaas.query.MpaasQueryFactory;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.mysql.cj.jdbc.MysqlDataSource;
import com.mysql.cj.jdbc.MysqlDataSourceFactory;
import com.xdap.keymen.config.PunchConfig;
import com.xdap.keymen.entity.*;
import com.xdap.keymen.entity.dayang.DaYangGroupBuyingEntity;
import com.xdap.keymen.utils.OKHttpUtils;
import com.xdap.motor.entity.SnowflakeIdWorker;
import com.xdap.motor.vo.ResponseVo;
import com.xdap.runtime.service.RuntimeAppContextService;
import com.xdap.runtime.service.RuntimeDatasourceService;
import com.xdap.runtime.service.RuntimeTokenService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import okhttp3.MediaType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.util.*;

@Service
@RequiredArgsConstructor
@Slf4j
public class PunchEmployeeService extends PunchBaseService{
    private final RuntimeDatasourceService runtimeDatasourceService;
    private final RuntimeAppContextService runtimeAppContextService;
    private final SnowflakeIdWorker snowflakeIdWorker;

    private final RuntimeTokenService runtimeTokenService;

    //private final PunchConfig punchConfig;

    private final PunchDeptService punchDeptService;

    @Autowired
    OKHttpUtils okHttpUtils;

    /**
     * 获取员工列表
     * @param upddate
     * @return
     */
    public ResponseVo getEmployeeList(String upddate) {
        //为空则到表中取
//        if (StringUtils.isEmpty(rv)) {
//            rv=getMaxRvid("2");
//        }
        Gson gson = new GsonBuilder().create();
        Map<String, String> params=new HashMap<>();
//        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//        params.put("startDate", startDate);
//        params.put("endDate",endDate);
        Map<String, String> headers=new HashMap<>();
        //每页条数
        int sz=100;
        //页面
        int pg=1;
        //记录总数
        //int maxCount=this.countEmployees(rv);
        int maxCount=800;
        log.info("最大记录数maxCount:{}",maxCount);
        // 计算总页数 (向上取整)
        int totalPages = (int) Math.ceil((double) maxCount / sz);
        for (int currentPage = pg; currentPage <= totalPages; currentPage++) {
            headers=new HashMap<>();
            headers.put("Authorization", "Bearer "+getPunchToken());
            //https://pisi.punch.com.cn:8498/CRM/api/CO/{rv}/{sz}/{pg}
            String response = okHttpUtils.doGet(getPunchUrl().concat("/CRM/api/hr/emp/"+upddate+"/"+sz+"/"+currentPage), params,headers);
            PunchResponse punchResponse = gson.fromJson(response, new TypeToken<PunchResponse>(){}.getType());
            //String result =punchResponse.getResult();
            List<PunchEmployeeResposeEntity> list = gson.fromJson(punchResponse.getResult(), new TypeToken<List<PunchEmployeeResposeEntity>>(){}.getType());
            for(PunchEmployeeResposeEntity punchOrderResponseEntity:list){
                saveDefanUser(punchOrderResponseEntity);
            }

            // 如果已经是最后一页，退出循环
            if (currentPage == totalPages) {
                break;
            }
        }

        return ResponseVo.ok().setData(maxCount);
    }


    private int countEmployees(Long rv) {
        int count=0;
        Gson gson = new GsonBuilder().create();
        Map<String, String> params=new HashMap<>();
        Map<String, String> headers=new HashMap<>();
        //https://pisi.punch.com.cn:8498/CRM/api/CO/Count/{rv}
        String response = okHttpUtils.doGet(getPunchUrl().concat("/CRM/api/hr/emp/count/"+rv.toString()), params,headers);
        PunchResponse punchResponse = gson.fromJson(response, new TypeToken<PunchResponse>(){}.getType());
        count=Integer.parseInt(punchResponse.getResult());
        return count;
    }

    private void saveDefanUser(PunchEmployeeResposeEntity entity){
        //归属营业部的，才创建
        PunchXdapDepartmentsEntity deptEntity=punchDeptService.getPunchXadpDept(entity.getFPersonDep());
        if (deptEntity!=null) {
            Map<String, Object> params=new HashMap<>();
            Gson gson = new GsonBuilder().create();
            List<DefanUserEntity> list=new ArrayList<>();
            DefanUserEntity defanUserEntity=new DefanUserEntity();
            defanUserEntity.setAccount(entity.getGonghao());
            defanUserEntity.setPassword("qwe123");
            defanUserEntity.setUsername(entity.getXingming());
            //defanUserEntity.setDepartmentCode("yingyebu");
            //defanUserEntity.setDepartmentId("101751023556778786816");
            defanUserEntity.setDepartmentCode(deptEntity.getDepartmentCode());
            defanUserEntity.setDepartmentId(deptEntity.getId());

            defanUserEntity.setUserNumber(entity.getGonghao());
            defanUserEntity.setUserStatus("ENABLE");
            //defanUserEntity.setEmail("");
            list.add(defanUserEntity);
            params.put("apiAddUsrDtoList",list);
            params.put("extendInfoVerify","false");

            //params.put("tenantIds","[\"733695865159417856\"]");



            //params=objectMapper.convertValue(params, Map.class);
            Map<String, String> headers=new HashMap<>();
            headers.put("xdaptoken", this.getDefanUserToken());
            headers.put("Content-Type", "application/json; charset=utf-8");
            headers.put("xdaptenantid", "733682782865195009");
            headers.put("xdaptimestamp", String.valueOf(Instant.now().toEpochMilli()));
            String url=this.getDefanUrl().concat("/backend/xdap-app/department/api/create/user");
            url="https://apaastest.punch.com.cn:8282/backend/xdap-app/department/api/create/user";
            //String response = okHttpUtils.doPost(url,params,headers);
            String strJson=gson.toJson(params);
            String response = okHttpUtils.doPostJson(url,strJson,headers, new HashMap<>());
            JsonObject jsonObject = gson.fromJson(response, JsonObject.class);
        }
    }

    // 作废，不通过这种方式同步用户
    private void saveOrUpdateEmployee(PunchEmployeeResposeEntity entity) {
        String currentTenantId = runtimeAppContextService.getCurrentTenantId();
        MpaasQuery query = runtimeDatasourceService.buildTenantMpaasQuery("xdap_app_" + currentTenantId);
        query.sql("select id from xdap_users where account='"+entity.getGonghao()+"'");
        String id= query.doQueryFirst(String.class);
        if (id!=null) {
            //更新
//            query = runtimeDatasourceService.buildTenantMpaasQuery("xdap_app_" + currentTenantId);
//            query.update("client_name",StringUtils.strip(entity.get()));
//            query.update("client_number",StringUtils.strip(entity.getCust_num()));
//            query.update("rvid",entity.getRvid());
//            query.update("last_update_date",new Date());
//            query.eq("sales_order_number", entity.getCo_num());
//            query.doUpdate(PunchOrderEntity.class);
        }else{
            //新增
            PunchEmployeeEntity punchEmployeeEntity = new PunchEmployeeEntity();
            punchEmployeeEntity.setId(snowflakeIdWorker.nextId());
            punchEmployeeEntity.setTenantId(currentTenantId);
            punchEmployeeEntity.setUsername(entity.getGonghao());
            punchEmployeeEntity.setAccount(entity.getGonghao());
            query = runtimeDatasourceService.buildTenantMpaasQuery("xdap_app_" + currentTenantId);
            query.doInsert(punchEmployeeEntity);
            //manage数据库
            PunchManageXadpUsers punchManageXadpUsers = new PunchManageXadpUsers();
            punchManageXadpUsers.setId(snowflakeIdWorker.nextId());
            punchManageXadpUsers.setUsername(entity.getXingming());
            punchManageXadpUsers.setAccount(entity.getGonghao());
            punchManageXadpUsers.setPassword("MjAwODIwRTMyMjc4MTVFRDE3NTZBNkI1MzFFN0UwRDI");
            punchManageXadpUsers.setRegisterTime(new Date());
            query = runtimeDatasourceService.buildTenantMpaasQuery("xdap_manage_database");
            query.doInsert(punchManageXadpUsers);



        }

    }

    public PunchEmployeeEntity getUserByGonghao(String gonghao) {
        String currentTenantId = runtimeAppContextService.getCurrentTenantId();
        return runtimeDatasourceService.buildTenantMpaasQuery("xdap_app_" + currentTenantId)
                .eq("account", gonghao)
                .doQueryFirst(PunchEmployeeEntity.class);
    }

    public ResponseVo syncUser() {
        String token="";
        Gson gson = new GsonBuilder().create();
        Map<String, String> params=new HashMap<>();
        Map<String, String> headers=new HashMap<>();
        headers.put("Content-Type", "application/json; charset=utf-8");
        //https://pisi.punch.com.cn:8498/CRM/api/CO/Count/{rv}
        String response = okHttpUtils.doPost("https://apaastest.punch.com.cn:8282/apaas/backend/test/test/xdap-open/token?grant_type=client_credentials&client_id=bb70a654-f082-482e-97da-6ceb1df56adc&client_secret=b80a8f85-47e0-4330-a46e-74b0e36ba8b3",params,headers);

        JsonObject jsonObject = gson.fromJson(response, JsonObject.class);
        token=jsonObject.get("access_token").getAsString();
        return ResponseVo.ok().setData(token);
    }


    private String getToken() {
        String token="";
        Gson gson = new GsonBuilder().create();
        Map<String, String> params=new HashMap<>();
        Map<String, String> headers=new HashMap<>();
        headers.put("Content-Type", "application/json; charset=utf-8");
        String response = okHttpUtils.doPost("https://apaastest.punch.com.cn:8282/apaas/backend/test/test/xdap-open/token?grant_type=client_credentials&client_id=bb70a654-f082-482e-97da-6ceb1df56adc&client_secret=b80a8f85-47e0-4330-a46e-74b0e36ba8b3",params,headers);
        JsonObject jsonObject = gson.fromJson(response, JsonObject.class);
        token=jsonObject.get("access_token").getAsString();
        return token;
    }
    public String test() {

        return getPunchToken();
    }
}
